﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Configuration;

using EncryptionServer.ProgramVersion;
using System.Text.RegularExpressions;

namespace EncryptionServer.Message
{
    public  class UDPMessage
    {
        
        public  static string CustomerName;

         static IPAddress groupAddress = IPAddress.Parse("255.255.255.255"); //广播地址

         static IPEndPoint ipep = new IPEndPoint(groupAddress, 8001);
         static UdpClient server = new UdpClient();
        /// <summary>
        /// 发送UDP
        /// </summary>
        public static void SendMessage()
        {
            if(1==1)
            { ;}
            else
            { ;}
            string version = string.Empty;
            string updatePath = string.Empty;            
            VersionManager.GetVersionNum(out version, out updatePath);
            byte[] data = new byte[1024];
            string computerName;
            IPAddress[] ipAddress;
            computerName = Dns.GetHostName();
            ipAddress = Dns.GetHostAddresses(computerName);
            string strIP = "";
            foreach (IPAddress ip in ipAddress)
            {
                if (Regex.IsMatch(ip.ToString(), @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$", RegexOptions.IgnoreCase))
                {
                    strIP = ip.ToString();
                    break;
                }

            }

            string connectString = ConfigurationManager.ConnectionStrings["newSampleYPDBEntities"].ConnectionString;
            //定义网络类型，数据连接类型和网络协议UDP
            string message = connectString;
            message = message.Substring(message.IndexOf("Data Source"));
            message = message.Substring(0, message.IndexOf(";MultipleActiveResultSets"));
            message = message + "|" + computerName + "(" + strIP + ")";
            message = message + "|" + version;
            message = message + "|" + updatePath;
            message = message + "|" + CustomerName;
            data = Encoding.Unicode.GetBytes(message);

            try
            {
                server.Send(data, data.Length, ipep);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
